import Toast from "../../miniprogram/miniprogram_npm/@vant/weapp/toast/toast";
import {Share} from "../../models/share";
import {Vote} from "../../models/vote";
import {Home} from "../../models/home";

function onPreview(e) {
    const {urls, current} = e.currentTarget.dataset
    wx.previewImage({
        urls,
        current
    })
}

async function onVote(e, callee) {
    const {type, id} = e.currentTarget.dataset
    const count = e.detail.count
    const res = await Vote.onVote(type, id, count)
    if(res.status === 200) {
        Toast.success({
            message: '助力成功',
            forbidClick: true
        })
        const currentCoin = callee.data.info.coin + count
        console.log(currentCoin);
        callee.setData({
            [`info.coin`]: currentCoin
        })
        callee.getOpenerEventChannel().emit('vote', {
            type,
            coin: currentCoin,
            id: e.currentTarget.dataset.id,
        })
    } else {
        Toast.fail({
            message: '助力失败',
            forbidClick: true
        })
    }
}

function onTapVoteButton(callee) {
    callee.setData({
        showVoteWindow: true
    })
}

function onCall(phoneNumber) {
    wx.makePhoneCall({
        phoneNumber
    })
}

function onInput(e, callee, bindField = 'info') {
    const {field} = e.currentTarget.dataset
    const value = e.detail.value ? e.detail.value : e.detail
    if (bindField) {
        callee.setData({
            [`${bindField}.${field}`]: value
        })
    } else {
        callee.setData({
            [field]: value
        })
    }
}

function onPageScroll(e, callee, field) {
    const isTop = callee.data[field]
    const top = e.scrollTop
    if (top === 0 && !isTop) {
        callee.setData({[field]: true})
    }
    if (top !== 0 && isTop) {
        callee.setData({[field]: false})
    }
}

async function onShare(e, title = undefined, path = undefined, callee) {
    if (!e) return
    const res = await Share.addCoinByShare()
    if (res && res.status === 200) {
        Toast.success({
            message: '领取一个币',
            forbidClick: true,
        })
        await onJudgeAccountSufficient(callee)
    }
    return {title, path}
}

async function onJudgeAccountSufficient(callee) {
    const res = await Home.getUserAccount()
    callee.setData({
        accountSufficient: res.coin > 0,
        currentAccount: res.coin
    })
    console.log(callee.data.accountSufficient, callee.data.currentAccount)
}

export {
    onPreview,
    onVote,
    onCall,
    onInput,
    onPageScroll,
    onShare,
    onTapVoteButton,
    onJudgeAccountSufficient
}
